<template>
  <div class="main-bg">
    <el-form ref="form" :model="queryParams" :inline="true" size="small">
      <el-form-item label="课程名称：" prop="courseName" >
        <el-input v-model="queryParams.courseName" clearable="" placeholder="请输入课程名称"></el-input>
      </el-form-item>
      <el-form-item label="课程专业：" prop="subjectIds" >
        <el-input v-model="queryParams.subjectIds" clearable="" placeholder="请输入课程专业"></el-input>
      </el-form-item>
      <el-form-item label="支付方式：" prop="payMode" >
        <el-select v-model="queryParams.payMode" placeholder="请选择">
          <el-option
            v-for="item in payModeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拼团状态：" prop="groupState" >
        <el-select v-model="queryParams.groupState" placeholder="请选择">
          <el-option
            v-for="item in groupStateArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程状态：" prop="courseState" >
        <el-select v-model="queryParams.courseState" placeholder="请选择">
          <el-option
            v-for="item in courseStateArr"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>



      <div style="float: right;">
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary"  size="mini" @click="addOrder">添加</el-button>
        </el-form-item>
      </div>



    </el-form>
    <div class="container">
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column
          prop="courseName"
          align="center"
          label="课程名称">
        </el-table-column>
        <el-table-column
          prop="subjectName"
          align="center"
          label="专业名称">
        </el-table-column>
        <el-table-column
          prop="groupOldNum"
          align="center"
          label="满员数量">
        </el-table-column>
        <el-table-column
          prop="groupNovNum"
          align="center"
          label="最新数量">
        </el-table-column>

        <el-table-column
          prop="groupStateEnum"
          align="center"
          label="拼团状态">
        </el-table-column>

        <el-table-column
          prop="overdueTypeEnum"
          align="center"
          label="过期类型">
        </el-table-column>
        <el-table-column
          prop="courseOldPrice"
          align="center"
          label="课程原价(元)">
        </el-table-column>
        <el-table-column
          prop="courseNovPrice"
          align="center"
          label="课程价格(元)">
        </el-table-column>
        <el-table-column
          prop="courseState"
          align="center"
          label="课程状态">
          <template slot-scope="scope">
            <p>{{scope.row.courseState==1002?'上架':'下架'}}</p>
          </template>
        </el-table-column>


        <el-table-column
          prop="goodsStatus"
          align="center"
          width="300"
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary"  size="mini" @click="goDetail(scope.row)">查看详情</el-button>
            <el-button type="primary"  size="mini" @click="editBtn(scope.row)">编辑</el-button>
            <el-button type="danger" v-if="scope.row.goodsStatus==1020"  size="mini" @click="updateStatus(scope.row)">上架</el-button>
            <el-button type="danger"  v-if="scope.row.goodsStatus==1002" size="mini" @click="updateStatus(scope.row)">下架</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="pageNum"
        style="float: right;margin-top: 20px;"
        :page-sizes="[10, 20, 50, 100]"

        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--查看-->
      <el-dialog title="查看详情" top="6vh" :visible.sync="seeFlag"  width="70%" append-to-body>
        <el-descriptions  :column="2"  border  class="my-label">
          <el-descriptions-item label="商品编号">{{form.goodsCode}}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{form.goodsName}}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{form.brandName}}</el-descriptions-item>
          <el-descriptions-item label="单位">{{form.unitsName}}</el-descriptions-item>
          <el-descriptions-item label="一级分类">{{form.classifyOneName}}</el-descriptions-item>
          <el-descriptions-item label="二级分类">{{form.classifyTwoName}}</el-descriptions-item>
          <el-descriptions-item label="采购金额">{{form.realityPrice}}</el-descriptions-item>
          <el-descriptions-item label="售卖金额">{{form.discountsPrice}}</el-descriptions-item>
          <el-descriptions-item label="库存">{{form.inventoryAmount}}</el-descriptions-item>
          <el-descriptions-item label="状态">{{form.goodsStatus==1002?'上架':'下架'}}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions  :column="1"  border  class="my-label">
          <el-descriptions-item label="标签">{{form.tagsNames}}</el-descriptions-item>
          <el-descriptions-item label="备注">{{form.remark}}</el-descriptions-item>


          <el-descriptions-item label="规格参数">
            <el-table :data="groupParams" style="width: 100%;margin-top: 20px;">
              <el-table-column prop="paramsSort" align="center" label="排序">
              </el-table-column>
              <el-table-column prop="paramsKey" align="center" label="参数名称">
              </el-table-column>
              <el-table-column prop="paramsValue" align="center" label="参数值">
              </el-table-column>
              <el-table-column prop="paramsUnit" align="center" label="单位">
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
        <el-carousel trigger="click" type="card" height="2  00px" >
          <el-carousel-item v-for="item in form.imageUrls" :key="item">
            <img :src="item" style="width: 100%;height:100%" alt="">
          </el-carousel-item>
        </el-carousel>
      </el-dialog>

      <!--编辑-->
      <el-dialog title="编辑" top="6vh" :visible.sync="editFlag"  width="70%" append-to-body class="my-label">
        <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="标签" prop="tagsNames">
            <el-select v-model="editForm.tags" @change="selectChangeMethod" multiple clearable filterable allow-create style="width:100%" placeholder="请选择">
              <el-option
                v-for="item in tagsList"
                :key="item.tagsId"
                :label="item.tagsName"
                :value="item.tagsId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售卖金额" prop="discountsPrice">
            <el-input v-model="editForm.discountsPrice"></el-input>
          </el-form-item>
          <el-form-item label="采购金额" prop="realityPrice">
            <el-input v-model="editForm.realityPrice"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark"></el-input>
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button type="primary" @click="submitForm('editForm')">确定</el-button>
            <el-button @click="editFlag=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-dialog :visible.sync="dialogTableVisible">
        <el-descriptions title="规格参数" :column="2"  border>
          <el-descriptions-item v-for="item in ParamsData" :label="item.paramsKey">{{item.paramsValue+item.paramsUnit}}</el-descriptions-item>

        </el-descriptions>
      </el-dialog>

      <el-dialog title="下单" :visible.sync="dialogFormVisible" width="1000px">
        <el-form :model="addorderData" :rules="saveFormRules"  ref="dataForm" label-width="100px">
          <el-form-item label="课程名称" prop="courseName">
            <el-input v-model="addorderData.courseName" clearable="" placeholder="请输入课程名称"></el-input>
          </el-form-item>
          <el-form-item label="课程专业" prop="subjectIds">
            <el-input v-model="addorderData.subjectIds" clearable="" placeholder="请输入课程专业"></el-input>
          </el-form-item>
          <el-form-item label="课程详情内容" prop="courseDescribe">
            <el-input v-model="addorderData.courseDescribe" clearable="" placeholder="请输入课程详情内容"></el-input>
          </el-form-item>
          <el-form-item label="课程封面" prop="courseImg">
            <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="addorderData.courseImg" :src="addorderData.courseImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="课程价格(元)" prop="courseNovPrice">
            <el-input v-model="addorderData.courseNovPrice" clearable="" placeholder="请输入课程价格(元)"></el-input>
          </el-form-item>
          <el-form-item label="课程原价(元)" prop="courseOldPrice">
            <el-input v-model="addorderData.courseOldPrice" clearable="" placeholder="请输入课程原价(元)"></el-input>
          </el-form-item>
          <el-form-item label="课程简介摘要" prop="courseSummary">
            <el-input v-model="addorderData.courseSummary" clearable="" placeholder="请输入课程简介摘要"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="groupEndTime">
            <el-date-picker
              style="width:100%"
              v-model="addorderData.groupEndTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="课程人数" prop="groupMin">
            <el-input v-model="addorderData.groupMin" clearable="" placeholder="请输入课程人数"></el-input>
          </el-form-item>
          <el-form-item label="拼团满员数量" prop="groupOldNum">
            <el-input v-model="addorderData.groupOldNum" clearable="" placeholder="请输入拼团满员数量"></el-input>
          </el-form-item>
          <el-form-item label="过期类型" prop="overdueType">
            <el-select v-model="queryParams.overdueType" placeholder="请选择">
              <el-option :key="1003" :label="'过期'" :value="1003"></el-option>
              <el-option :key="1030" :label="'不过期'" :value="1030"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="过期时间" prop="overdueTime" v-if="queryParams.overdueType==1003">
            <el-date-picker
              style="width:100%"
              v-model="addorderData.overdueTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="支付方式" prop="payMode">
            <el-select v-model="queryParams.payMode" placeholder="请选择">
              <el-option :key="1900" :label="'线上'" :value="1900"></el-option>
              <el-option :key="1901" :label="'线下'" :value="1901"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维度" prop="courseLatitude">
            <el-input v-model="addorderData.courseLatitude" clearable="" placeholder="请输入维度"></el-input>
          </el-form-item>
          <el-form-item label="经度" prop="courseLongitude">
            <el-input v-model="addorderData.courseLongitude" clearable="" placeholder="请输入经度"></el-input>
          </el-form-item>
          <el-form-item label="课程地址" prop="courseAddress">
            <el-input v-model="addorderData.courseAddress" clearable="" placeholder="请输入课程地址"></el-input>
          </el-form-item>
          <el-form-item label="省" prop="courseProvince">
            <el-select style="width:100%" v-model="addorderData.courseProvince" @change="getCity" placeholder="请选择">
              <el-option
                v-for="item in provinceArr"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="courseCity" v-if="addorderData.courseProvince">
            <el-select style="width:100%" v-model="addorderData.courseCity" @change="getArea" placeholder="请选择">
              <el-option
                v-for="item in cityArr"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区" prop="courseArea" v-if="addorderData.courseCity">
            <el-select style="width:100%" v-model="addorderData.courseArea"  placeholder="请选择">
              <el-option
                v-for="item in areaArr"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitOrder('dataForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import { getAdminCoursePageList, saveCourse, provinceList, provinceUpCityList, cityUpAreaList } from '@/api/class'
  import { saveParentSubject } from '@/api/major'
import { getToken } from "@/utils/auth";
  export default {
    name: "InventoryManage",
    data(){
      return{
        uploadUrl: process.env.VUE_APP_BASE_API + "oss/uploadFileImg", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(), //headers属性中添加token，这个属性是el-upload自带的用来设置上传请求头部
        },
        dialogFormVisible:false,
        dialogTableVisible:false,
        ParamsData:{},
        seeFlag:false,
        groupStateArr:[{
          value:1004,
          label:'开始',
        },{
          value:1045,
          label:'成功',
        },{
          value:1049,
          label:'失败',
        }],
        payModeArr:[{
          value:1900,
          label:'线上',
        },{
          value:1901,
          label:'线下',
        }],
        courseStateArr:[{
          value:1002,
          label:'上架',
        },{
          value:1020,
          label:'下架',
        }],
        categoryList: [],
        queryParams:{},
        pageNum:1,
        total:0,
        loading:true,
        checked:false,
        tableData:[],
        brandList:[],
        form:{},
        groupParams:[],
        editFlag:false,
        editForm:{},
        classifyArr: [],
        classifyArrTwo: [],
        goodsList: [],
        addressList:[],
        tagsList:[],
        provinceArr:[],
        cityArr:[],
        areaArr:[],
        addorderData: {},
        rules:{
          discountsPrice: [
            { required: true, message: '请输入售卖金额', trigger: 'blur' },
          ],
          realityPrice: [
            { required: true, message: '请输入采购金额', trigger: 'blur' },
          ],
        },
        saveFormRules: {
          courseName: {
            required: true, message: '请输入课程名称', trigger: 'blur'
          },
        },
      }
    },
    mounted(){
      this.getList()
      // this.getBrand()
      // this.getClassify()
      // this.getParentCategoryAllSelectList()
      // this.getWholesaleBuyStatusAll()
    },
    methods:{
      handleAvatarSuccess(res, file) {

        // this.addorderData.courseImg = res.body
        this.$set(this.addorderData,'courseImg',res.body)
        console.log(this.addorderData.courseImg)
        this.$message({
          type: 'success',
          message: '上传成功!'
        });
      },
      beforeAvatarUpload(file) {
        console.log(file.type)
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      getCity(){
        let body={
          provinceCode:this.addorderData.courseProvince
        }
        provinceUpCityList({body}).then(res => {
          this.cityArr=res.body
        })
      },
      getArea(){
        let body={
          cityCode:this.addorderData.courseCity
        }
        cityUpAreaList({body}).then(res => {
          this.areaArr=res.body
        })
      },
      changeClassifyTwo(){
        this.getGoodsList()
      },
      searchSelect(val){

        this.addorderData.orderGoodsBos=val
      },
      // 获取商品列表
      getGoodsList() {
        let body = {
          pageSize: 10000,
          pageNum: 1,
          table: {
            "classifyTwoId": this.addorderData.classifyTwoId, //一级分类id
            "storeCoding": localStorage.getItem('storeCoding')
          }
        }
        getInventoryGoodsStatusPageList({ body }).then(res => {
          this.goodsList = res.body.list

        })

      },
      // 分类触发规格
      async categoryChange(val) {
        let body = {
          "parentId": val,
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getSonCategoryByParent({ body }).then(res => {
          this.classifyArrTwo = res.body

        })
      },
      // 分类下来
      async getParentCategoryAllSelectList() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getParentCategoryAll({ body }).then(res => {
          this.classifyArr = res.body

        })
      },
      // 获取地址列表
      async getWholesaleBuyStatusAll() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getWholesaleBuyStatusAll({ body }).then(res => {
          this.addressList = res.body

        })
      },
      addOrder(){

        provinceList().then(res => {
          this.provinceArr=res.body
        })

        this.addorderData={
          courseName:''
        }
        this.dialogFormVisible=true
      },
      // 查看参数
      checkParams(data){
        var arr=JSON.parse(data);
        this.ParamsData=arr
        console.log(this.ParamsData)
        this.dialogTableVisible=true
      },
      selectChangeMethod(){
        this.$forceUpdate()
      },
      // 上下架
      async updateStatus(row){
        let body={
          inventoryId:row.inventoryId,
          discountsPrice:row.discountsPrice,
          goodsStatus:row.goodsStatus==1020?'1002':1020,
          storeCoding: localStorage.getItem('storeCoding')
        }
        let res = await updateInventoryStatus({body})
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
        this.getList()
      },
      submitOrder(formName){

        this.$refs[formName].validate((valid) => {
          if (valid) {
            let body={
              ...this.addorderData
            }
            saveCourse({ body }).then(res => {
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              this.dialogFormVisible=false
            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 编辑提交
      submitForm(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            console.log(this.editForm)
            var tagsNameArr=[]
            for (var i=0;i<this.editForm.tags.length;i++){
              for (var j=0;j<this.tagsList.length;j++){
                if(this.editForm.tags[i]==this.tagsList[j].tagsId){
                  tagsNameArr.push(this.tagsList[j].tagsName)
                }
              }
            }

            let body={
              ...this.editForm,
              tagsIds:this.editForm.tags.toString(),
              tagsNames:tagsNameArr.toString()
            }
            let res = await updateInventoryStatus({body})
            this.$message({
              type: 'success',
              message: '修改成功!'
            });

            this.getList()
            this.editFlag=false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 查看详情
      async goDetail(row){
        let body={
          "inventoryId": row.inventoryId ,
          "storeCoding": localStorage.getItem('storeCoding')
        }
        let res = await getInventoryGoodsDetails({body})
        this.form=res.body
        this.groupParams=JSON.parse(this.form.groupParams)
        this.seeFlag=true
      },
      async editBtn(row){
        let body={
          "inventoryId": row.inventoryId ,
          "storeCoding": localStorage.getItem('storeCoding')
        }
        let res = await getInventoryGoodsDetails({body})
        this.editForm={...res.body}
        this.editForm.tags=res.body.tagsIds==''?'':res.body.tagsIds.split(',');
        this.getTags(row)


      },
      async getTags(row){
        let body={
          "storeCoding":  localStorage.getItem('storeCoding'),
          "categoryId": row.classifyOneId
        }
        let data = await getTagsAll({body})
        this.tagsList=data.body
        this.editFlag=true
      },
      // 获取品牌
      getBrand() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding')
        }
        getBrandAll({ body }).then(res => {
          this.brandList=res.body
        })

      },
      // 获取所有一级分类
      async getClassify(){
        let body={
          storeCoding:localStorage.getItem('storeCoding')
        }
        let res = await getParentCategoryAll({body})
        this.categoryList=res.body
      },
      async getList(){
        var that=this
        console.log(this.pageNum)
        let body={
          pageSize:10,
          pageNum:this.pageNum,
          table:{
            ...this.queryParams,
          }
        }

        let res = await getAdminCoursePageList({body})
        that.tableData=res.body.list
        this.loading=false
        that.total=res.body.totalCount
      },
      handleQuery(){
        this.pageNum=1
        this.getList()
      },
      handleDelete(row){
        var that=this
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let body={
            incomeId:row.incomeId
          }
          axios.post('api/vegetable_income/deleteIncome',{
            body
          }).then(function (res) {

              if (res.data.code==2000){
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                that.getList()
              }else{
                that.$message.error(res.data.msg);
              }
            }
          )

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });


      },

      timestampToTime(timestamp) {
        var time = this.dayjs(timestamp).format("YYYY-MM-DD");
        // var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        // var Y = date.getFullYear() + '-';
        // var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        // var D = date.getDate() + ' ';
        return time;
      },
      handleCurrentChange(val){
        this.pageNum=val
        this.getList()
      }
    },
  }
</script>

<style scoped>
  .titlebox{
    color:#20384D;
    font-size: 16px;
    display: flex;
    align-items: center;
    margin-bottom: 30px;
  }
  .titlebar{
    width: 4px;
    height: 16px;
    background: #035EBA;
    border-radius: 0 2px 2px 0;
    margin-right: 10px;
  }
  .titleline{
    flex: 1;
    height: 2px;
    background: #E6E9EE;
    margin-left: 20px;
  }
  .upload-tips{
    color: #999999;
    line-height: 20px;
  }
  ::v-deep .avatar-uploader .el-upload {
     border: 1px dashed #d9d9d9;
     border-radius: 6px;
     cursor: pointer;
     position: relative;
     overflow: hidden;
   }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
